package com.shop.cloud.controller.system;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shop.cloud.auth0.jwt.Token;
import com.shop.cloud.auth0.jwt.TokenGenerator;
import com.shop.cloud.auth0.jwt.exceptions.JWTCreationException;
import com.shop.cloud.common.mybatis.BaseController;
import com.shop.cloud.common.token.PasswordHashUtil;
import com.shop.cloud.dao.hongfu.ShopDao;
import com.shop.cloud.domain.hongfu.Shop;
import com.shop.cloud.domain.system.SysLoginHistory;
import com.shop.cloud.domain.system.SysPosition;
import com.shop.cloud.domain.system.SysResource;
import com.shop.cloud.domain.system.SysRoleResource;
import com.shop.cloud.domain.system.SysUser;
import com.shop.cloud.domain.system.SysUserRole;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.filter.IgnoreAuth;
import com.shop.cloud.model.request.LoginRequest;
import com.shop.cloud.security.EncodeUtil;
import com.shop.cloud.service.system.ISysPositionService;
import com.shop.cloud.service.system.ISysResourceService;
import com.shop.cloud.service.system.ISysRoleResourceService;
import com.shop.cloud.service.system.ISysUserRoleService;
import com.shop.cloud.service.system.ISysUserService;
import com.shop.cloud.service.system.impl.SysLoginHistoryService;
import com.shop.cloud.util.CookieManager;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.MagicConstants;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

@RestController
@RequestMapping
public class HomeController extends BaseController {

	@Autowired
	private ISysResourceService sysResourceService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private ISysPositionService sysPositionService;
	@Autowired
	private ShopDao shopDao;
	
	@Autowired
	private ISysRoleResourceService sysRoleResourceService;
	
	@Autowired
	private SysLoginHistoryService sysLoginHistoryService;
 
	@IgnoreAuth
	@RequestMapping(value = "leftMenu")
	@ResponseBody
	public Response leftMenu(HttpServletRequest request,@CurrentUserId Long userId) {
		List<SysResource> permissionrs = sysResourceService.findMenusByUserId(userId);
		List<SysResource> datas = new ArrayList<SysResource>();
		if (permissionrs != null) {
			for (SysResource permission : permissionrs) {
				if (permission.getParentId() == null) {
					for (SysResource p : permissionrs) {
						if (permission.getId()==p.getParentId()) {
							permission.getResources().add(p);
						}
					}
					datas.add(permission);
				}
			}
		}
		return ResponseUtil.ok(datas);
	}

	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(@CurrentUserId Long userId, HttpServletRequest request) {
		SysUser user = sysUserService.get(userId);
		request.setAttribute("user", user);
		return "index";
	}

	@IgnoreAuth
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(value = "forgetPassword", method = RequestMethod.GET)
	public String forgetPassword() {
		return "main/forgetPassword";
	}
	
	@RequestMapping(value = "welcome", method = RequestMethod.GET)
	public String welcome(@CurrentUserId Long userId,HttpServletRequest request) {
		return "main/welcome";
	}
	
	@IgnoreAuth
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public Response login(HttpServletRequest request, HttpServletResponse response, @RequestBody LoginRequest loginRequest) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		Map<String, Object> map = new HashMap<String, Object>();
		String username = loginRequest.getUsername();
		String password = loginRequest.getPassword();
		if (StringUtils.isEmpty(username)) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		if (StringUtils.isEmpty(password)) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		Map<String, Object> findUser = new HashMap<String, Object>();
		findUser.put("username", username);
		findUser.put("password", EncodeUtil.encodeMD5(password));
		
		SysUser user = sysUserService.findUser(findUser);
		
		if (user == null) {
			return ResponseUtil.error(ErrorCode.USER_NOT_ERROR);
		}
		if (user.getStatus() == 1) {
			return ResponseUtil.error(ErrorCode.USER_NOT_LOGINED2);
		}
		
		//暂时屏蔽
//		if (!PasswordHashUtil.validatePassword(password, user.getPassword())) {
//			return ResponseUtil.error(ErrorCode.USER_PASSWORD_INVALID);
//		}
		
		List<SysResource> resources=sysResourceService.findPermissionsByUserId(user.getId());
		Map<String, Object> claims=new HashMap<String, Object>();
    	claims.put(MagicConstants.SESSION_USER_ID,user.getId());
    	List<String> aList=new ArrayList<String>();
    	for (SysResource resource : resources) {
			if(StringUtils.isEmpty(resource.getUrl())){
				aList.add(resource.getUrl());
			}
		}
    	claims.put(MagicConstants.SESSION_USER_PERMISSIONS,aList);
    	Token token=TokenGenerator.create(claims);
    	new CookieManager(request, response).setCookie(MagicConstants.USER_TOKEN, token.getToken(), 7*24*60*60);
    	
    	//根据用户 id 得到 职位信息
    	//查询用户职位是否有
		SysUserRole sysUserRole = new SysUserRole();
		sysUserRole.setUserId(user.getId());
		
		
		//根据当前userId得到职位关系
		List<SysUserRole> sysUserList= sysUserRoleService.find(sysUserRole);
	
		SysRoleResource sysRoleResource = new SysRoleResource();
		sysRoleResource.setPositionId(sysUserList.get(0).getPositionId());
		//查询用户是否有权限
		List<SysRoleResource> sysRoleResourceList = sysRoleResourceService.find(sysRoleResource);
		if(sysRoleResourceList.size()<=0){
		 return ResponseUtil.error(ErrorCode.USER_NOT_POSITION);
		}
		
		SysPosition sysPosition = new SysPosition();
		sysPosition.setId(sysUserList.get(0).getPositionId());
		List<SysPosition> sysPositionList = sysPositionService.find(sysPosition);
    	
		//判断是否是2
		if(sysPositionList.get(0).getAuthority() == 2){
			SysUserRole userRoleEntity = new SysUserRole();
			userRoleEntity.setRoleId(sysUserList.get(0).getRoleId());
			
			//通过角色得到用户
			List<SysUserRole>  userRoleList = sysUserRoleService.find(userRoleEntity); 
			Long[] aArrayUserId = new Long[userRoleList.size()];
			Long[] aArrayPositionId = new Long[userRoleList.size()];
			for(int i=0;i<userRoleList.size();i++){
				aArrayUserId[i] = userRoleList.get(i).getUserId();
				aArrayPositionId[i] = userRoleList.get(i).getPositionId();
			}
			//当前登陆店员数组
			map.put("role",userRoleList.get(0).getRoleId());			
			map.put("positionIds", aArrayPositionId);
			map.put("userIds", aArrayUserId);
		}
        //加入登录时间记录
		SysLoginHistory sysLoginHistory = new SysLoginHistory();
		sysLoginHistory.setUserId(user.getId());
		Date date = new Date();
		sysLoginHistory.setLoginTime(new Timestamp(date.getTime()));
		sysLoginHistoryService.insert(sysLoginHistory);
		
		
		
		
    	map.put("authority", sysPositionList.get(0).getAuthority());
    	map.put("token", token);
		return ResponseUtil.ok(map);
	}

	@RequestMapping(value = "lockScreen", method = RequestMethod.GET)
	public String lockScreen(@CurrentUserId Long userId, HttpServletRequest request) throws NoSuchAlgorithmException, InvalidKeySpecException {
		SysUser user = sysUserService.get(userId);
		request.setAttribute("user", user);
		return "main/lockscreen";
	}

	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) throws NoSuchAlgorithmException, InvalidKeySpecException {
		return "redirect:/login";
	}

	@RequestMapping(value = "sendVerifCode", method = RequestMethod.POST)
	@ResponseBody
	public Response sendVerifCode(String phone, String token, String password) {
		SysUser findUser = new SysUser();
		findUser.setPhone(phone);
		SysUser sysUser = sysUserService.findOne(findUser);
		if (sysUser == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS);
		}
		String code = RandomStringUtils.randomNumeric(4);
		// cacheService.setVerifCode(phone, code);
		return ResponseUtil.ok(code);
	}

	@RequestMapping(value = "unLockScreen", method = RequestMethod.POST)
	@ResponseBody
	public Response unLockScreen( Long id, String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
		 if (id == null) {
			 return ResponseUtil.error(ErrorCode.USER_NOT_LOGINED);
			 }
		 SysUser user = sysUserService.get(id);
		 if (user == null) {
		 return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS);
		 }
		 if (StringUtils.isEmpty(password)) {
			 return ResponseUtil.error(ErrorCode.USER_PASSWORD_INVALID);
		 }
		 if (!PasswordHashUtil.validatePassword(password, user.getPassword())) {
		 return ResponseUtil.error(ErrorCode.USER_PASSWORD_INVALID);
		 }
		return ResponseUtil.ok();
	}

}
